<template>
	<view>
		<view class="">
			<tn-form :model="form" ref="form" :labelWidth="180" :errorType="['message', 'toast']">
				<view class="card tn-padding-sm tn-margin-sm">
					<tn-form-item label="时间：" prop="createTime1">
					  <uni-datetime-picker :clearIcon="false" :border="false" placeholder="请选择时间"
										   v-model="form.createTime1" />
					</tn-form-item>
					<tn-form-item label="被查人员：" prop="personUnderInvest">
						<view class="tn-flex tn-flex-direction-column">
							<tn-tag shape="radius" backgroundColor="#0a47c4" fontColor="#fff"  v-for="(item, index) of bzry" :key="item.value" margin="10rpx"
									width="auto" class="tn-padding-right-sm">
							  <view class="tn-flex tn-flex-direction-row tn-flex-col-center tn-flex-row-center">
								<view>{{ item.label }}</view>
								<view class="tn-margin-left-lg tn-text-xs" @click="remove('bzry',index)">删除</view>
							  </view>
							</tn-tag>
						</view>
						<tn-input type="select" :selectOpen="bzryShow" @click="bzryShow = true"></tn-input>
					</tn-form-item>
					<tn-form-item label="检查时间：" prop="checkTime">
						<uni-datetime-picker :border="false" type="date" placeholder="请选择检查时间" v-model="form.checkTime" />
					</tn-form-item>
					<tn-form-item label="检查人员：" prop="inspector">
						<view class="tn-flex tn-flex-direction-column">
													<tn-tag shape="radius" backgroundColor="#0a47c4" fontColor="#fff" v-for="(item, index) of jcry" :key="item.value" margin="10rpx"
															width="auto" class="tn-padding-right-sm">
													  <view class="tn-flex tn-flex-direction-row tn-flex-col-center tn-flex-row-center">
														<view>{{ item.label }}</view>
														<view class="tn-margin-left-lg tn-text-xs" @click="remove('jcry',index)">删除</view>
													  </view>
													</tn-tag>
												</view>
												<tn-input type="select" :selectOpen="jcryShow" @click="jcryShow = true"></tn-input>
					</tn-form-item>
					<tn-form-item label="记录人：" prop="recorder">
						<view class="tn-flex tn-flex-direction-column">
													<tn-tag  shape="radius" backgroundColor="#0a47c4" fontColor="#fff" v-for="(item, index) of jlry" :key="item.value" margin="10rpx"
															width="auto" class="tn-padding-right-sm">
													  <view class="tn-flex tn-flex-direction-row tn-flex-col-center tn-flex-row-center">
														<view>{{ item.label }}</view>
														<view class="tn-margin-left-lg tn-text-xs" @click="remove('jlry',index)">删除</view>
													  </view>
													</tn-tag>
												</view>
												<tn-input type="select" :selectOpen="jlryShow" @click="jlryShow = true"></tn-input>
					</tn-form-item>
				</view>
				<view class="card tn-padding-sm tn-margin-sm">
					<tn-form-item label="检查情况和存在问题(文字描述)：" prop="question">
						<tn-input type="textarea" v-model="form.question" />
					</tn-form-item>

					<tn-form-item label="整改意见：" prop="rectComments">
						<tn-input type="textarea" v-model="form.rectComments" />
					</tn-form-item>
					<tn-form-item label="检查负责人：" prop="rectCommentsPerson">
						<image class="signImg" @click="jupmSign('rectCommentsPerson')" :src="form.rectCommentsPerson" mode=""></image>
					</tn-form-item>
				</view>
				<view class="card tn-padding-sm tn-margin-sm">
					<tn-form-item label="整改措施落实情况：" prop="rectMeasures">
						<tn-input type="textarea" v-model="form.rectMeasures" />
					</tn-form-item>
					<tn-form-item label="负责人：" prop="rectMeasuresPerson">
						<image class="signImg" @click="jupmSign('rectMeasuresPerson')" :src="form.rectMeasuresPerson" mode=""></image>
					</tn-form-item>

					<tn-form-item label="整改结果验证：" prop="rectResults">
						<tn-input type="textarea" v-model="form.rectResults" />
					</tn-form-item>
					<tn-form-item label="验证人：" prop="rectResultsPerson">
						<image class="signImg" @click="jupmSign('rectResultsPerson')" :src="form.rectResultsPerson" mode=""></image>
					</tn-form-item>
				</view>
				<view class="tn-flex tn-flex-row-center tn-padding-xl">
				  <tn-button @click="submit" backgroundColor="tn-bg-blue" style="width: 80%" fontColor="tn-color-white">保存
				  </tn-button>
				</view>
			</tn-form>
		</view>
		<tn-modal v-model="erweima" :custom="true">
			<view class="custom-modal-content tn-flex tn-flex-direction-column tn-flex-col-center">
				<p style="margin-bottom: 8px;">现场安全管理检查记录</p>

				<canvas id="qrcode" canvas-id="qrcode" style="width: 200px; height: 200px;"></canvas>
				<tn-button @click="downloadPDFFn" backgroundColor="tn-bg-blue" style="width: 80%;margin-top: 16px;" fontColor="tn-color-white">
					下载PDF
				</tn-button>
			</view>
		</tn-modal>
		<!-- 被查人员select -->
				<view v-show="bzryShow">
					<tn-select v-model="bzryShow" mode="single" :list="selectList"
						@confirm="(event)=>selectConfirm('bzry',event)"></tn-select>
				</view>

				<!-- 检查人员select -->
				<view v-show="jcryShow">
					<tn-select v-model="jcryShow" mode="single" :list="selectList"
						@confirm="(event)=>selectConfirm('jcry',event)"></tn-select>
				</view>

				<!-- 记录人员select -->
				<view v-show="jlryShow">
					<tn-select v-model="jlryShow" mode="single" :list="selectList"
						@confirm="(event)=>selectConfirm('jlry',event)"></tn-select>
				</view>
	</view>
</template>

<script>
import { getJySiteSafetyLog, addJySiteSafetyLog } from '@/api/jySiteSafetyLog';
import UQRCode from '@/node_modules/uqrcodejs/uqrcode.js';
import config from '@/config';
	import {
		userList
	} from '@/api/login.js';
	import dayjs from 'dayjs';
import {downPdf, erweimaUrl} from "@/api/exam";
import {saveNextStep} from "@/pages/rescue/add/funtion";
export default {
	data() {
		return {
			selectList:[],
						bzryShow: false,
						bzry: [],

						jcryShow: false,
						jcry: [],

						jlryShow: false,
						jlry: [],

			dragAddress: '',
			erweima: false,
			form: {
				createTime1:'',
				personUnderInvest: '',
				checkTime: '',
				inspector: '',
				recorder: '',
				question: '',
				rectComments: '',
				rectCommentsPerson: '',
				rectMeasures: '',
				rectMeasuresPerson: '',
				rectResults: '',
				rectResultsPerson: ''
			},
			rules: {
				// personUnderInvest: [{
				// 	required: true,
				// 	message: '请输入被查人员',
				// 	// 可以单个或者同时写两个触发验证方式
				// 	trigger: ['change'],
				// }],
				// checkTime: [{
				// 	required: true,
				// 	message: '请选择检查时间',
				// 	// 可以单个或者同时写两个触发验证方式
				// 	trigger: ['change'],
				// }],
				// inspector: [{
				// 	required: true,
				// 	message: '请输入检查人员',
				// 	// 可以单个或者同时写两个触发验证方式
				// 	trigger: ['change'],
				// }],
				// recorder: [{
				// 	required: true,
				// 	message: '请输入记录人',
				// 	// 可以单个或者同时写两个触发验证方式
				// 	trigger: ['change'],
				// }],
			}
		};
	},
	watch:{
			bzry(val){
				let arr = [];
				val.forEach((item) => {
					arr.push(item.label)
				});
				this.form.personUnderInvest = arr.join()
			},
			jcry(val){
				let arr = [];
				val.forEach((item) => {
					arr.push(item.label)
				});
				this.form.inspector = arr.join()
			},
			jlry(val){
				let arr = [];
				val.forEach((item) => {
					arr.push(item.label)
				});
				this.form.recorder = arr.join()
			}
		},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.getUserList();
		this.$refs.form.setRules(this.rules);
		uni.getStorage({
			key: 'TIANBAOID',
			success: (res) => {
				console.log(res.data);
				if (res.data) {
					this.getList(res.data);
					this.form.jyBaseId = res.data;
				}
			}
		});
	},
	onNavigationBarButtonTap(e) {
    // 08.12 解决卷宗修改车牌，数据不同步问题
		 this.submit('pdf');
	},
	methods: {
		remove(key,index) {
					this[key].splice(index, 1);
				},
				selectConfirm(key,event) {
					this[key] = [...this[key], ...event];
				},
				getUserList() {
					userList({
						current: 1,
						size: 999
					}).then((res) => {
						const arr = [];
						res.data.records.forEach((item) => {
							arr.push({
								value: item.id,
								label: item.realName
							});
						});
						this.selectList = arr;
					});
				},
		downloadPDFFn() {
			const fileUrl = downPdf({
        baseId: this.form.jyBaseId,
        typeName: 'jcjl',
        id: undefined
      });
			// 创建一个隐藏的 <a> 元素用于下载
			const link = document.createElement('a');
			link.href = fileUrl;
			link.download = '安全记录.pdf'; // 设置下载的文件名
			link.style.display = 'none';
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			uni.showToast({
				title: '下载成功',
				icon: 'success'
			});
		},
		creatImg() {
			// 获取uQRCode实例
			var qr = new UQRCode();
			// 设置二维码内容
			qr.data = erweimaUrl({
        baseId: this.form.jyBaseId,
        typeName: 'jcjl',
        id: undefined
      });;
			// 设置二维码大小，必须与canvas设置的宽高一致
			qr.size = 200;
			// 调用制作二维码方法
			qr.make();
			// 获取canvas上下文
			var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件，this必须传入
			// 设置uQRCode实例的canvas上下文
			qr.canvasContext = canvasContext;
			// 调用绘制方法将二维码图案绘制到canvas上
			qr.drawCanvas();
		},
		jupmSign(name) {
			uni.navigateTo({
				url: '/pages/signBoard/signBoard?name=' + name,
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					acceptDataFromOpenedPage: (data) => {
						this.form[data.name] = data.data;
					}
				}
			});
		},
		getList(id) {
			getJySiteSafetyLog(id).then((res) => {
				if (res.data) {
					this.form = res.data;
					this.dragAddress = true;
					if(res.data.personUnderInvest){
						const arr = res.data.personUnderInvest.split(",")
						this.bzry =arr.map(item=>{return {value:item,label:item}})
					}

					if(res.data.inspector){
						const arr = res.data.inspector.split(",")
						this.jcry =arr.map(item=>{return {value:item,label:item}})
					}

					if(res.data.recorder){
						const arr = res.data.recorder.split(",")
						this.jlry =arr.map(item=>{return {value:item,label:item}})
					}
				}else{
          this.form.createTime1 =  dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
			});
		},
		submit(type) {
			this.$refs.form.validate((valid) => {
				if (valid) {
					addJySiteSafetyLog(this.form).then((res) => {
						saveNextStep(type, res, this)
					});
					console.log('验证通过');
				} else {
					console.log('验证失败');
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.card {
	background-color: #fff;
	box-shadow: 0px 4px 20px 0px rgba(0, 3, 72, 0.1);
	border-radius: 8px;
}
::v-deep{
		.tn-form-item--left__content__label{
			font-weight: 700;
		}
	}
</style>
